package com.yungu.swift.order.utils;


import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by JXJ on 2018/4/25.
 */
public class SmsTaskHelper {

    private static final Logger logger = LoggerFactory.getLogger(SmsTaskHelper.class);

    private static ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors() * 2,
            new BasicThreadFactory.Builder().namingPattern("smsTask-schedule-pool-%d").daemon(true).build());

    public static void execute(Runnable task) {
        executor.submit(task);
        logger.debug("【短信线程池任务】线程池中线程数：" + executor.getPoolSize());
        logger.debug("【短信线程池任务】队列中等待执行的任务数：" + executor.getQueue().size());
        logger.debug("【短信线程池任务】已执行完任务数：" + executor.getCompletedTaskCount());
    }


    /**
     * 关闭线程池
     */
    public static void shutdown() {
        logger.debug("shutdown pool...");
        executor.shutdown();
        try {
            if (!executor.isTerminated()) {
                logger.debug("直接关闭失败[" + executor.toString() + "]");
                executor.awaitTermination(3, TimeUnit.SECONDS);
                if (executor.isTerminated()) {
                    logger.debug("成功关闭[" + executor.toString() + "]");
                } else {
                    logger.debug("[" + executor.toString() + "]关闭失败，执行shutdownNow...");
                    if (executor.shutdownNow().size() > 0) {
                        logger.debug("[" + executor.toString() + "]没有关闭成功");
                    } else {
                        logger.debug("shutdownNow执行完毕，成功关闭[" + executor.toString() + "]");
                    }
                }
            } else {
                logger.debug("成功关闭[" + executor.toString() + "]");
            }
        } catch (InterruptedException e) {
            logger.warn("接收到中断请" + executor.toString() + "停止操作");
        }
    }

}
